﻿namespace DesignModeConsole.行为型.解释器模式.告警规则进阶;

/// <summary>
/// and 表达式
/// </summary>
public class AndExpression2 : IAlertRuleExpression2
{
    private readonly List<IAlertRuleExpression2> _expressions = new List<IAlertRuleExpression2>();

    public AndExpression2(string strAndExpression)
    {
        var strExpressions = strAndExpression.Split("&&");
        foreach (var e in strExpressions)
        {
            if (e.Contains('>'))
            {
                _expressions.Add(new DaYuExpression2(e));
            }
            else if (e.Contains('<'))
            {
                _expressions.Add(new XiaoYuExpression2(e));
            }
            else if (e.Contains('='))
            {
                _expressions.Add(new EqualExpression2(e));
            }
            else
            {
                throw new ArgumentException("表达式无效");
            }
        }
    }

    public AndExpression2(IEnumerable<string> param)
    {
        var strExpressions = string.Join(" ", param).Split("&&");
        foreach (var e in strExpressions)
        {
            if (e.Contains('>'))
            {
                _expressions.Add(new DaYuExpression2(e));
            }
            else if (e.Contains('<'))
            {
                _expressions.Add(new XiaoYuExpression2(e));
            }
            else if (e.Contains('='))
            {
                _expressions.Add(new EqualExpression2(e));
            }
            else
            {
                throw new ArgumentException("表达式无效");
            }
        }
    }

    public AndExpression2(IEnumerable<IAlertRuleExpression2> expressions)
    {
        _expressions.AddRange(expressions);
    }

    public bool Interpret(Dictionary<string, long> statusDic)
    {
        return _expressions.All(item => item.Interpret(statusDic));
    }
}

/// <summary>
/// or 表达式
/// </summary>
public class OrExpression : IAlertRuleExpression2
{
    private readonly List<IAlertRuleExpression2> _expressions = new List<IAlertRuleExpression2>();

    public OrExpression(string strOrExpression)
    {
        var andExpressions = strOrExpression.Split("||");
        foreach (var andExpr in andExpressions)
        {
            _expressions.Add(new AndExpression2(andExpr));
        }
    }

    public OrExpression(IEnumerable<IAlertRuleExpression2> expressions)
    {
        _expressions.AddRange(expressions);
    }

    public bool Interpret(Dictionary<string, long> statusDic)
    {
        return _expressions.Any(item => item.Interpret(statusDic));
    }
}